package com.gitee.wsl.android.ext

import android.app.ActivityManager
import com.gitee.wsl.android.ext.device.activityManager
import timber.log.Timber

object ServiceExt {
    /**
     * 判断服务是否运行
     * @param clazz [Class]
     * @return `true` yes, `false` no
     */
    inline fun <reified T:Class<*>> isServiceRunning(clazz:T): Boolean {
        return  isServiceRunning(clazz.name)
    }

    /**
     * 判断服务是否运行
     * @param className package.ServiceClassName ( class.getName() )
     * @return `true` yes, `false` no
     */
    fun isServiceRunning(className: String): Boolean {
        try {
            val activityManager: ActivityManager =  ApplicationInit.application.activityManager
            val lists: List<ActivityManager.RunningServiceInfo> = activityManager.getRunningServices(Int.MAX_VALUE)
            for (info in lists) {
                if (className == info.service.className) return true
            }
        } catch (e: java.lang.Exception) {
            Timber.d(  e, "isServiceRunning")
        }
        return false
    }


    // =
    /**
     * 获取所有运行的服务
     * @return 服务名集合
     */
    fun getAllRunningService(): Set<String> {
        try {
            val names: MutableSet<String> = HashSet()
            val activityManager: ActivityManager = ApplicationInit.application.activityManager
            val lists: List<ActivityManager.RunningServiceInfo> = activityManager.getRunningServices(Int.MAX_VALUE)
            for (info in lists) {
                names.add(info.service.className)
            }
            return names
        } catch (e: java.lang.Exception) {
            Timber.d(e, "getAllRunningService")
        }
        return emptySet()
    }
}